package utils


/**
 * String 的扩展函数，将蛇形转换为大驼峰
 */
fun String.snakeToCamel(): String {
    val str = removeInvalidCharacter()
    if (str.isEmpty()) { return str }
    val words = str.split("_").toMutableList()
    if (words.first().first().isDigit()) {
        words[0] = "n" + words[0]
    }
    return words.joinToString("") { word ->
        word.replaceFirstChar { if (it.isLowerCase()) it.uppercaseChar() else it }
    }
}

/**
 * String 的扩展函数，将蛇形转换为小驼峰
 */
fun String.snakeToLowerCamel(): String {
    val str = removeInvalidCharacter()
    if (str.isEmpty()) { return str }
    val words = str.split("_").toMutableList()
    if (words.first().first().isDigit()) {
        words[0] = "n" + words[0]
    }
    return words.joinToString("") { word ->
        word.replaceFirstChar { if (it.isLowerCase()) it.uppercaseChar() else it }
    }.let {
        it[0].lowercaseChar() + it.substring(1)
    }
}

// 删除 String 中不合法的字符
fun String.removeInvalidCharacter(): String {
    // 不使用正则
    return String(toCharArray().filter { it.isLetterOrDigit() || it == '_' }.toCharArray())
}